package com.waitingresult.aliyun.ocr;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * All right reserved,Designed By WangShuai
 *
 * @author : WangShuai
 * @version : V1.0
 * @ClassName : BusinessLicense
 * @Description : 图片转文字
 * @date : 2021/8/9 8:46
 */
public class BusinessLicense {
    public static void main(String[] args) {
        String host = "https://dm-58.data.aliyun.com";
        String path = "/rest/160601/ocr/ocr_business_license.json";
        String appcode = "aa064b6b97231231s2312a3ddb6eb1314f7934fd5";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + appcode);
        headers.put("Content-Type", "application/json; charset=UTF-8");
        String imgBase64 = imgBase64("C:\\Users\\Administrator\\Downloads\\yyzz.jpg");
        JSONObject requestObj = new JSONObject();
        requestObj.put("image", imgBase64);

        String bodys = requestObj.toString();
        try {
            HttpResponse response = HttpUtil.createPost(host + path).headerMap(headers, true).body(bodys).execute();
            String body = response.body();
            System.err.println(body);
            //获取response的body
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String imgBase64(String path) {
        /**
         *  对path进行判断，如果是本地文件就二进制读取并base64编码，如果是url,则返回
         */
        String imgBase64 = "";
        if (path.startsWith("http")) {
            imgBase64 = path;
        } else {
            try {
                File file = new File(path);
                byte[] content = new byte[(int) file.length()];
                FileInputStream finputstream = new FileInputStream(file);
                finputstream.read(content);
                finputstream.close();
                imgBase64 = Base64.encode(content);
            } catch (IOException e) {
                e.printStackTrace();
                return imgBase64;
            }
        }

        return imgBase64;
    }
}
